<template>
  <div class="page-section">
    <!-- 顶部：只选择老人 -->
    <div class="flex justify-end mb-4">
      <el-select
        v-model="selectedElderlyId"
        placeholder="选择老人"
        filterable
        remote
        reserve-keyword
        :remote-method="filterElderlyOptions"
        @focus="handleElderlyFocus"
        style="width: 240px;"
      >
        <el-option
          v-for="item in elderlyOptions"
          :key="item.id"
          :label="item.fullName"
          :value="item.id"
        />
      </el-select>
    </div>

    <!-- 用药统计面板 -->
    <el-card shadow="never" class="mb-6">
      <template #header>
        <span class="text-lg font-bold">用药统计</span>
      </template>
      <div class="grid grid-cols-3 gap-4 p-4">
        <el-card class="chart-card">
          <div ref="chart1" class="chart"></div>
        </el-card>
        <el-card class="chart-card">
          <div ref="chart2" class="chart"></div>
        </el-card>
        <el-card class="chart-card">
          <div ref="chart3" class="chart"></div>
        </el-card>
      </div>
    </el-card>

    <!-- 用药记录管理 & 提醒 -->
    <el-card shadow="never" class="mb-6">
      <template #header>
        <div class="flex items-center justify-between">
          <span class="text-lg font-bold">用药记录管理</span>
          <div>
            <el-button type="primary" @click="openForm()">添加记录</el-button>
            <el-button
              type="success"
              @click="setupReminder()"
              :disabled="!selectedElderlyId"
            >设置每日提醒</el-button>
          </div>
        </div>
      </template>

      <!-- 只保留按药品名称搜索 -->
      <el-form :inline="true" :model="searchForm" class="mb-4">
        <el-form-item label="药品名称">
          <el-input
            v-model="searchForm.drugName"
            placeholder="药品名称"
            @input="handleSearchInput"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="fetchData">搜索</el-button>
          <el-button plain @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="recordList" stripe border>
        <!-- 重新加回老人姓名列 -->
        <el-table-column label="老人姓名" width="120">
          <template #default>
            {{ selectedElderlyName }}
          </template>
        </el-table-column>

        <el-table-column prop="drugName"    label="药品名称" />
        <el-table-column prop="dosage"      label="剂量" />
        <el-table-column prop="frequency"   label="频次" />
        <el-table-column label="开始日期">
          <template #default="{ row }">{{ formatDate(row.startDate) }}</template>
        </el-table-column>
        <el-table-column label="结束日期">
          <template #default="{ row }">{{ formatDate(row.endDate) }}</template>
        </el-table-column>
        <el-table-column prop="cost" label="总价（元）" />
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="openForm(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteRecord(row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="mt-4"
        layout="total, prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
        background
      />
    </el-card>

    <!-- 添加/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="老人姓名" prop="elderlyUserId">
          <el-select
            v-model="formData.elderlyUserId"
            filterable
            remote
            reserve-keyword
            :remote-method="filterElderlyOptionsForForm"
            placeholder="请输入老人姓名"
            @focus="handleElderlyFocusForForm"
            :key="'elderly-' + formData.elderlyUserId"
          >
            <el-option
              v-for="item in elderlyOptionsForForm"
              :key="item.id"
              :label="item.fullName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="药品名称" prop="drugId">
          <el-select
            v-model="formData.drugId"
            filterable
            remote
            reserve-keyword
            :remote-method="filterDrugOptions"
            placeholder="请输入药品名称"
            @focus="handleDrugFocus"
            @change="handleDrugSelect"
            :key="'drug-' + formData.drugId"
          >
            <el-option
              v-for="item in drugOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="剂量" prop="dosage">
          <el-input v-model="formData.dosage" />
        </el-form-item>

        <el-form-item label="频次" prop="frequency">
          <el-input v-model="formData.frequency" />
        </el-form-item>

        <el-form-item label="药品价格" prop="cost">
          <el-input v-model="formData.cost" placeholder="请输入价格" />
        </el-form-item>

        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker v-model="formData.startDate" type="date" />
        </el-form-item>

        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker v-model="formData.endDate" type="date" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import dayjs from 'dayjs'
import * as echarts from 'echarts'

// 格式化日期
const formatDate = v => (v ? dayjs(v).format('YYYY-MM-DD') : '-')

// ========== 顶部老人下拉 ==========
const selectedElderlyId   = ref(null)
const allElderlyList      = ref([])
const elderlyOptions      = ref([])

// 计算当前老人姓名
const selectedElderlyName = computed(() => {
  const e = allElderlyList.value.find(i => i.id === selectedElderlyId.value)
  return e?.fullName || ''
})

async function fetchAllElderly() {
  try {
    const res = await axios.get('/api/medicine/record/elderly-list')
    allElderlyList.value = res.data || []
    elderlyOptions.value = allElderlyList.value
    if (allElderlyList.value.length && selectedElderlyId.value == null) {
      selectedElderlyId.value = allElderlyList.value[0].id
    }
  } catch (e) {
    console.error('获取老人列表失败:', e)
  }
}

function filterElderlyOptions(query) {
  elderlyOptions.value = query
    ? allElderlyList.value.filter(i => i.fullName.includes(query))
    : allElderlyList.value
}

function handleElderlyFocus() {
  if (!allElderlyList.value.length) fetchAllElderly()
  filterElderlyOptions('')
}

// 监听老人切换
watch(selectedElderlyId, id => {
  if (id) {
    onElderlyChange()
    fetchData()
  }
})

// ========== 图表部分 ==========
const chart1 = ref(null)
const chart2 = ref(null)
const chart3 = ref(null)
let instance1, instance2, instance3

function initCharts() {
  nextTick(() => {
    if (chart1.value) {
      instance1 = echarts.init(chart1.value)
      instance1.setOption({ 
        title: { text: '月度用药剂量趋势', left: 'center' },
        xAxis: { type: 'category', data: [] }, 
        yAxis: { type: 'value' },
        series: [{ type: 'line', smooth: true, data: [] }] 
      })
    }
    
    if (chart2.value) {
      instance2 = echarts.init(chart2.value)
      instance2.setOption({ 
        title: { text: '药品类型分布', left: 'center' },
        tooltip: {}, 
        legend: { orient: 'vertical', left: 'left' },
        series: [{ type: 'pie', radius: '50%', data: [] }] 
      })
    }
    
    if (chart3.value) {
      instance3 = echarts.init(chart3.value)
      instance3.setOption({ 
        title: { text: '每日费用变化', left: 'center' },
        xAxis: { type: 'category', data: [] }, 
        yAxis: { type: 'value' },
        series: [{ type: 'bar', data: [] }],
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          formatter: '{b}: {c} 元'
        }
      })
    }
  })
}

async function onElderlyChange() {
  if (!selectedElderlyId.value) return
  try {
    const { data } = await axios.get('/api/medicine/record/stats', {
      params: { elderlyUserId: selectedElderlyId.value }
    })
    // 更新折线
    if (instance1) {
      instance1.setOption({
        xAxis: { data: data.line.map(i => i.name) },
        series: [{ data: data.line.map(i => i.value) }]
      })
    }
    // 更新饼图
    if (instance2) {
      instance2.setOption({
        series: [{ data: data.pie.map(i => ({ name: i.name, value: i.value })) }]
      })
    }
    // 更新柱状
    if (instance3) {
      instance3.setOption({
        xAxis: { data: data.bar.map(i => i.name) },
        series: [{ data: data.bar.map(i => i.value) }]
      })
    }
  } catch {
    ElMessage.error('获取统计数据失败')
  }
}

// ========== 用药记录管理 ==========
const searchForm  = reactive({ drugName: '' })
const recordList  = ref([])
const total       = ref(0)
const currentPage = ref(1)
const pageSize    = ref(10)

async function fetchData() {
  if (!selectedElderlyId.value) return
  
  try {
    const res = await axios.get('/api/medicine/record/list', {
      params: {
        elderlyUserId: selectedElderlyId.value,
        drugName: searchForm.drugName,
        page: currentPage.value,
        pageSize: pageSize.value
      }
    })
    recordList.value = res.data.data
    total.value = res.data.total
  } catch (e) {
    ElMessage.error('获取用药记录失败')
  }
}

function handleSearchInput() {
  currentPage.value = 1
  fetchData()
}

function handlePageChange(page) {
  currentPage.value = page
  fetchData()
}

function resetSearch() {
  searchForm.drugName = ''
  fetchData()
}

// ========== 弹窗表单相关 ==========
const dialogVisible = ref(false)
const formRef = ref()
const formData = reactive({
  id: null,
  elderlyUserId: '',
  drugId: '',
  drugName: '',
  dosage: '',
  frequency: '',
  startDate: '',
  endDate: '',
  cost: ''
})

const dialogTitle = computed(() => {
  return formData.id ? '编辑用药记录' : '添加用药记录'
})

const rules = {
  elderlyUserId: [{ required: true, message: '请选择老人', trigger: 'change' }],
  drugId: [{ required: true, message: '请选择药品', trigger: 'change' }],
  dosage: [{ required: true, message: '请输入剂量', trigger: 'blur' }],
  frequency: [{ required: true, message: '请输入频次', trigger: 'blur' }],
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }]
}

// ========== 表单中的老人选择 ==========
const elderlyOptionsForForm = ref([])

function filterElderlyOptionsForForm(query) {
  elderlyOptionsForForm.value = query
    ? allElderlyList.value.filter(i => i.fullName.includes(query))
    : allElderlyList.value
}

function handleElderlyFocusForForm() {
  if (!allElderlyList.value.length) fetchAllElderly()
  filterElderlyOptionsForForm('')
}

// ========== 药品选择相关 ==========
const allDrugList = ref([])
const drugOptions = ref([])

async function fetchAllDrugs() {
  try {
    const res = await axios.get('/api/medicine/info/search')
    allDrugList.value = res.data || []
    drugOptions.value = res.data || []
  } catch (e) {
    console.error('获取药品列表失败:', e)
  }
}

function filterDrugOptions(query) {
  drugOptions.value = query
    ? allDrugList.value.filter(i => i.name.includes(query))
    : allDrugList.value
}

function handleDrugFocus() {
  if (!allDrugList.value.length) fetchAllDrugs()
  filterDrugOptions('')
}

function handleDrugSelect(drugId) {
  const selectedDrug = allDrugList.value.find(item => item.id === drugId)
  if (selectedDrug) {
    formData.drugName = selectedDrug.name
    if (selectedDrug.price) {
      formData.cost = selectedDrug.price
    }
  }
}

// ========== CRUD 操作 ==========
async function openForm(record = null) {
  // 先加载所有选项数据
  await Promise.all([fetchAllElderly(), fetchAllDrugs()])
  
  if (record) {
    // 编辑模式
    let elderlyUserId = record.elderlyUserId
    let drugId = record.drugId
    
    // 如果没有elderlyUserId，根据elderlyName查找
    if (!elderlyUserId && record.elderlyName) {
      const elderlyItem = allElderlyList.value.find(item => item.fullName === record.elderlyName)
      elderlyUserId = elderlyItem?.id || ''
    }
    
    // 如果没有drugId，根据drugName查找
    if (!drugId && record.drugName) {
      const drugItem = allDrugList.value.find(item => item.name === record.drugName)
      drugId = drugItem?.id || ''
    }
    
    Object.assign(formData, {
      id: record.id,
      elderlyUserId: elderlyUserId,
      drugId: drugId,
      drugName: record.drugName,
      dosage: record.dosage,
      frequency: record.frequency,
      startDate: record.startDate,
      endDate: record.endDate,
      cost: record.cost
    })
    
    await nextTick()
    
    // 确保选项中包含当前选中的数据
    if (elderlyUserId) {
      ensureElderlyInFormOptions(elderlyUserId)
      elderlyOptionsForForm.value = [...allElderlyList.value]
    }
    
    if (drugId) {
      ensureDrugInOptions(drugId)
      drugOptions.value = [...allDrugList.value]
    }
  } else {
    // 添加模式
    Object.assign(formData, {
      id: null,
      elderlyUserId: selectedElderlyId.value || '', // 默认选中当前老人
      drugId: '',
      drugName: '',
      dosage: '',
      frequency: '',
      startDate: '',
      endDate: '',
      cost: ''
    })
  }
  
  // 设置表单选项
  elderlyOptionsForForm.value = [...allElderlyList.value]
  drugOptions.value = [...allDrugList.value]
  
  dialogVisible.value = true
}

function ensureElderlyInFormOptions(elderlyUserId) {
  if (!elderlyUserId) return
  
  const exists = elderlyOptionsForForm.value.find(item => item.id === elderlyUserId)
  if (!exists) {
    const elderlyItem = allElderlyList.value.find(item => item.id === elderlyUserId)
    if (elderlyItem) {
      elderlyOptionsForForm.value = [elderlyItem, ...elderlyOptionsForForm.value]
    }
  }
}

function ensureDrugInOptions(drugId) {
  if (!drugId) return
  
  const exists = drugOptions.value.find(item => item.id === drugId)
  if (!exists) {
    const drugItem = allDrugList.value.find(item => item.id === drugId)
    if (drugItem) {
      drugOptions.value = [drugItem, ...drugOptions.value]
    }
  }
}

async function submitForm() {
  formRef.value.validate(async valid => {
    if (!valid) return
    
    // 修正日期格式
    formData.startDate = dayjs(formData.startDate).format('YYYY-MM-DD')
    formData.endDate = dayjs(formData.endDate).format('YYYY-MM-DD')
    
    try {
      if (formData.id) {
        await axios.put('/api/medicine/record/update', formData)
        ElMessage.success('编辑成功')
      } else {
        await axios.post('/api/medicine/record/add', formData)
        ElMessage.success('添加成功')
      }
      dialogVisible.value = false
      fetchData()
      onElderlyChange() // 刷新图表
    } catch (e) {
      ElMessage.error('保存失败')
    }
  })
}

async function deleteRecord(id) {
  try {
    await ElMessageBox.confirm('确定删除该记录？', '提示', { type: 'warning' })
    await axios.delete(`/api/medicine/record/delete/${id}`)
    ElMessage.success('删除成功')
    fetchData()
    onElderlyChange() // 刷新图表
  } catch {
    ElMessage.info('已取消')
  }
}

// 提醒功能
function setupReminder() {
  ElMessage.success(`已为老人 ${selectedElderlyName.value} 设置每日 9:00 用药提醒`)
}

// 初始化
onMounted(async () => {
  await fetchAllElderly()
  initCharts()
  // 选中第一个后，立即加载一次数据
  if (selectedElderlyId.value) {
    await onElderlyChange()
    fetchData()
  }
})
</script>

<style scoped>
.page-section { padding: 16px }
.chart { width: 100%; height: 300px }
.chart-card { padding: 8px }
</style>